<template>
  <div class="cart-wrapper">
    <!-- 头部 -->
    <header>
      <div class="header-left">
        <h3>购物车</h3>
        <span class="location" @click="toSelectAddress">
          {{ addressDisplay }} >
        </span>
      </div>
      <div class="manage-cart" @click="toggleManage">
        {{ isManaging ? '完成' : '管理' }}
      </div>
    </header>

    <!-- 购物车列表 -->
    <div class="cart-list">
      <div v-for="business in groupedCartItems" :key="business.businessId" class="business-box">
        <div class="business-info">
          <h4 class="business-name">{{ business.businessName }}</h4>
          <p class="business-address">{{ business.businessAddress }}</p>
        </div>
        <div v-for="item in business.items" :key="item.cartId" class="cart-item">
          <div class="item-checkbox">
            <input 
              type="checkbox" 
              v-model="item.selected"
            />
          </div>
          <img :src="handleImageUrl(item.foodImage)" alt="商品图片" class="item-image" />
          <div class="item-details">
            <h5>{{ item.foodName }}</h5>
            <p class="food-spec">规格：{{ item.foodSpec }}</p>
            <p class="food-price">¥{{ item.foodPrice }}</p>
            <div class="quantity-control">
              <button @click="decreaseQuantity(item)" class="quantity-button">-</button>
              <span>{{ item.quantity }}</span>
              <button @click="increaseQuantity(item)" class="quantity-button">+</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部结算/删除 -->
    <div class="cart-footer">
      <div class="total-price" v-if="!isManaging">
        合计: ¥{{ totalPrice.toFixed(2) }}
      </div>
      <button 
        :class="['action-button', isManaging ? 'delete-button' : 'checkout-button']"
        @click="handleAction"
      >
        {{ isManaging ? `删除${selectedCount ? `(${selectedCount})` : ''}` : '结算' }}
      </button>
    </div>

    <!-- Footer -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import Footer from "../components/Footer.vue";
import { 
  listCartByUserIdService, 
  updateCartService, 
  deleteCartService 
} from '../api/cart';
import { getBusinessByIdService } from '../api/business';
import { getFoodByIdService } from '../api/food';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { getAddressById } from '../api/address';
import { useUserInfoStore } from '../stores/user';
import { createOrder } from '../api/orders';
import { handleImageUrl } from '@/utils/imageUtils';

const cartItems = ref([]);
const businessInfo = ref({});
const foodInfo = ref({});
const isManaging = ref(false);
const router = useRouter();
const route = useRoute();
const selectedAddress = ref(null);
const userInfoStore = useUserInfoStore();

// 获取购物车数据
const fetchCartItems = async () => {
  try {
    const response = await listCartByUserIdService({ userId: userInfoStore.userInfo.id });
    cartItems.value = response.data.map(item => ({
      ...item,
      selected: false,
      foodPrice: 0,
      foodName: '',
      foodSpec: ''
    }));
    await Promise.all([
      fetchBusinessInfo(),
      fetchFoodInfo()
    ]);
    updateCartItemsWithFoodInfo();
  } catch (error) {
    console.error('获取购物车数据失败:', error);
  }
};

// 更新购物车项的食品信息
const updateCartItemsWithFoodInfo = () => {
  cartItems.value = cartItems.value.map(item => {
    const food = foodInfo.value[item.foodId] || {};
    return {
      ...item,
      foodPrice: food.foodPrice || item.price,
      foodName: food.foodName || '未知商品',
      foodSpec: food.foodSpec || '默认规格',
      foodImage: food.foodImg || ''
    };
  });
};

// 获取商家信息
const fetchBusinessInfo = async () => {
  try {
    const businessIds = [...new Set(cartItems.value.map(item => item.businessId))];
    for (const businessId of businessIds) {
      const response = await getBusinessByIdService({ businessId });
      businessInfo.value[businessId] = response.data;
    }
  } catch (error) {
    console.error('获取商家信息失败:', error);
  }
};

// 获取食品信息
const fetchFoodInfo = async () => {
  try {
    const foodIds = [...new Set(cartItems.value.map(item => item.foodId))];
    for (const foodId of foodIds) {
      const response = await getFoodByIdService(foodId);
      foodInfo.value[foodId] = response.data;
    }
  } catch (error) {
    console.error('获取食品信息失败:', error);
  }
};

// 按商家分组购物车商品
const groupedCartItems = computed(() => {
  const groups = {};
  cartItems.value.forEach(item => {
    if (!groups[item.businessId]) {
      const business = businessInfo.value[item.businessId] || {};
      groups[item.businessId] = {
        businessName: business.businessName || '未知商家',
        businessAddress: business.businessAddress || '未知地址',
        businessId: item.businessId,
        items: []
      };
    }
    groups[item.businessId].items.push(item);
  });
  return Object.values(groups);
});

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    if (item.selected) {
      return total + (item.foodPrice || 0) * item.quantity;
    }
    return total;
  }, 0);
});

const increaseQuantity = (item) => {
  item.quantity++;
  updateCartItem(item);
};

const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity--;
    updateCartItem(item);
  }
};

// 更新购物车商品数量
const updateCartItem = async (item) => {
  try {
    await updateCartService({
      cartId: item.cartId,
      foodId: item.foodId,
      businessId: item.businessId,
      userId: item.userId,
      quantity: item.quantity
    });
  } catch (error) {
    console.error('更新购物车数据失败:', error);
  }
};

// 计算选中的商品数量
const selectedCount = computed(() => {
  return groupedCartItems.value.reduce((count, business) => {
    return count + business.items.filter(item => item.selected).length;
  }, 0);
});

// 切换管理模式
const toggleManage = () => {
  isManaging.value = !isManaging.value;
};

// 处理结算或删除操作
const handleAction = async () => {
  if (isManaging.value) {
    // 删除操作
    if (selectedCount.value === 0) {
      ElMessage.warning('请选择要删除的商品');
      return;
    }

    try {
      await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedCount.value} 个商品吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );

      // 收集要删除的商品 ID 并执行删除
      const deletePromises = [];
      groupedCartItems.value.forEach(business => {
        business.items.forEach(item => {
          if (item.selected) {
            deletePromises.push(deleteCartService(item.cartId));
          }
        });
      });

      // 等待所有删除操作完成
      await Promise.all(deletePromises);

      ElMessage.success('删除成功');
      
      // 删除成功后刷新购物车数据
      await fetchCartItems();
      
      // 删除完成后退出管理模式
      isManaging.value = false;

    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请重试');
      }
    }
  } else {
    // 结算操作
    if (!selectedAddress.value) {
      ElMessage.error('请选择配送地址');
      return;
    }

    // 检查是否有选中的商品
    const selectedItems = cartItems.value.filter(item => item.selected);
    if (selectedItems.length === 0) {
      ElMessage.error('请选择要结算的商品');
      return;
    }

    // 按商家分组处理订单
    const businessOrders = {};
    selectedItems.forEach(item => {
      if (!businessOrders[item.businessId]) {
        const business = businessInfo.value[item.businessId] || {};
        businessOrders[item.businessId] = {
          businessId: item.businessId,
          userId: userInfoStore.userInfo.id,
          orderTotal: 0,
          deliveryPrice: business.deliveryPrice || 0,
          orderItems: []
        };
      }
      
      businessOrders[item.businessId].orderItems.push({
        foodId: item.foodId,
        quantity: item.quantity,
        foodPrice: item.foodPrice
      });
      
      businessOrders[item.businessId].orderTotal += item.foodPrice * item.quantity;
    });

    try {
      // 创建订单
      const orderPromises = Object.values(businessOrders).map(orderData => {
        // 加上配送费
        orderData.orderTotal += orderData.deliveryPrice;
        return createOrder(orderData);
      });

      const results = await Promise.all(orderPromises);
      
      // 检查所有订单是否创建成功
      const failedOrders = results.filter(res => res.code !== 0);
      if (failedOrders.length > 0) {
        ElMessage.error('部分订单创建失败');
        return;
      }

      // 获取第一个订单的ID（如果有多个订单，跳转到第一个订单的支付页面）
      const firstOrderId = results[0].data;
      
      // 跳转到支付页面
      router.push({
        path: '/payment',
        query: { 
          orderId: firstOrderId,
          addressId: selectedAddress.value.daId
        }
      });

    } catch (error) {
      console.error('创建订单失败:', error);
      ElMessage.error('创建订单失败，请重试');
    }
  }
};

// 跳转到地址选择页面
const toSelectAddress = () => {
  router.push({
    path: '/address',
    query: { from: 'cart' }
  });
};

// 获取地址详情
const fetchAddress = async (addressId) => {
  try {
    const res = await getAddressById(addressId);
    selectedAddress.value = res.data;
  } catch (error) {
    console.error('获取地址详情失败:', error);
  }
};

// 在 script setup 中添加处理地址的逻辑
onMounted(() => {
  fetchCartItems();
  // 如果有地址参数，更新选中的地址
  const { addressId, addressName, addressPhone, addressDetail } = route.query;
  if (addressId) {
    selectedAddress.value = {
      daId: addressId,
      contactName: addressName,
      contactTel: addressPhone,
      address: addressDetail
    };
  }
});

// 修改地址显示的计算属性
const addressDisplay = computed(() => {
  if (selectedAddress.value) {
    return selectedAddress.value.address;
  }
  return '手动选择地址';
});
</script>

<style scoped>
.cart-wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  padding-bottom: 20vw; /* 确保有足够的空间显示 Footer */
  overflow-y: auto;
}

header {
  width: 100%;
  height: 12vw;
  background-color: #ff7043;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  padding: 0 4vw;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.header-left h3 {
  font-size: 4.5vw;
  font-weight: bold;
}

.location {
  font-size: 3.2vw;
  color: rgba(255, 255, 255, 0.8);
}

.manage-cart {
  font-size: 3.8vw;
  color: #fff;
  cursor: pointer;
}

.cart-list {
  padding: 3vw;
}

.business-box {
  background-color: #fff;
  margin-bottom: 3vw;
  border-radius: 2vw;
  padding: 3vw;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.business-name {
  font-size: 4.5vw;
  color: #333;
  margin-bottom: 1vw;
}

.business-address {
  font-size: 3vw;
  color: #999;
  margin-bottom: 2vw;
}

.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
  padding: 2vw;
  border-radius: 2vw;
  /* background-color: #f9f9f9; */
}

.item-checkbox {
  margin-right: 2vw;
}

.item-image {
  width: 20vw;
  height: 20vw;
  margin-right: 3vw;
  border-radius: 2vw;
  object-fit: cover;
  border: 1px solid #ddd;
}

.item-details {
  flex: 1;
}

.item-details h5 {
  font-size: 4vw;
  color: #333;
  margin-bottom: 1vw;
}

.food-spec {
  font-size: 3vw;
  color: #999;
  margin-bottom: 1vw;
}

.food-price {
  font-size: 4vw;
  color: #ff7043;
  font-weight: bold;
  margin-bottom: 1vw;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-button {
  width: 4vw;
  height: 4vw;
  background-color: #ff7043; /* 主题色 */
  color: #fff;
  border: none;
  border-radius: 50%;
  font-size: 3.5vw;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.quantity-control span {
  margin: 0 2vw;
  font-size: 4vw;
  color: #333;
}

.cart-footer {
  position: fixed; /* 使用 fixed 定位 */
  bottom: 13vw; /* 确保在 Footer 上方 */
  width: 100%;
  display: flex;
  justify-content: flex-end; /* 改为靠右对齐 */
  align-items: center;
  padding: 3vw;
  background-color: #fff;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #f2eeee; /* 添加下边框 */
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  box-sizing: border-box;
  gap: 3vw; /* 添加间距 */
}

.total-price {
  font-size: 4vw;
  color: #333;
  margin-right: auto; /* 让总价靠左 */
}

.action-button {
  padding: 2vw 4vw;
  border-radius: 2vw;
  font-size: 4vw;
  cursor: pointer;
  border: none;
  transition: all 0.3s;
  color: #fff;
}

.checkout-button {
  background-color: #ff7043;
}

.delete-button {
  background-color: #ff4646;
}
</style> 